<?php
/* 
 * Auther Bachue
 * This PHP file contains three functions about htpasswd file.
 * You can list, add, and delete user in htpasswd.
 */

include_once './config/config.php';
include_once './config/dbconf.php';

/*
 * function listUser()
 * Auther Bachue
 * Description: This function read htpasswd file and then List All User
 * Return:an array includes all user or false if file opens error.
 */
function listUser()
{
    global $config;
    $file=file($config['HtPasswdFilePath']);
    if(empty($file))
    {
        //TODO do log here!
        return false;
    }
    $userlist=array();
    foreach($file as $line)
    {
        /*
         * contents in htpasswd file like this:
         *
         * dev1:/04Z9mrBqCyns
         * dev2:jZKNZnPMF9QpA
         * dev3:WpdZrNS24ttsA
         * dev4:V3E1i28.Mk2ck
         * 
         * we just get the username before ':'
         */
        $array=explode(':', $line);
        $userlist[]=$array[0];
    }
    return $userlist;
}

/*
 * function addUser($username,$password)
 * Auther Bachue
 * Description: This function execute shell command htpasswd
 *              to add a new user or modify password of an existed user
 * Return:htpasswd output info
 */
function addUser($username,$password)
{
    $username=trim($username);
    $password=trim($password);
    if(empty($username) || empty($password)) return 'username and password can\'t be empty';
    if(!preg_match(VALID_REGEX, $username) ||
       strpos($password, ';')!==false ||
       strpos($password, '|')!==false ||
       strpos($password, '`')!==false ||
       strpos($password, '$')!==false)
    {
        return 'username and password can\'t contain any illegal character';
    }
    
    global $config;
    $info='';
    if(!file_exists($config['HtPasswdFilePath']))
    {
        $info=shell_exec("{$config['HtPasswdPath']} -bcm '{$config['HtPasswdFilePath']}' '{$username}' '{$password}' 2>&1 1> /dev/null");
    }
    else
    {
        $info=shell_exec("{$config['HtPasswdPath']} -bm '{$config['HtPasswdFilePath']}' '{$username}' '{$password}' 2>&1 1> /dev/null");
    }

    return $info;
}

/*
 * function deleteUser($username)
 * Auther Bachue
 * Description: This function execute shell command htpasswd
 *              to delete an existed user
 *              of course, if the username you given is not existed, some error info will be return
 * Return: htpasswd output info
 */
function deleteUser($username)
{
    $username=trim($username);
    if(empty($username)) return 'username can\'t be empty';
    if(!preg_match(VALID_REGEX, $username))
    {
        return 'username can\'t contain any illegal character';
    }

    global $config;
    return shell_exec("{$config['HtPasswdPath']} -D '{$config['HtPasswdFilePath']}' '{$username}' 2>&1 1> /dev/null");
}

?>
